package com.sir.tao.carhire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sir.tao.carhire.dao.AdministratorsDao;
import com.sir.tao.carhire.entity.table.AdministratorsEntity;
import com.sir.tao.carhire.service.AdministratorsService;
import com.sir.tao.carhire.shiro.JwtUtil;
import com.sir.tao.carhire.util.RedisUtil;
import com.sir.tao.carhire.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author dyy
 * @data 2021/12/27 9:49
 * @description:
 */
@Service
public class AdministratorsServiceImpl extends ServiceImpl<AdministratorsDao, AdministratorsEntity> implements AdministratorsService {

    @Resource
    private AdministratorsDao administratorsDao;
    @Resource
    private RedisUtil redisUtil;


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean login(AdministratorsEntity administratorsEntity) {

        String password = administratorsEntity.getPassword();
        AdministratorsEntity trueAdministrators = getOne(new LambdaQueryWrapper<AdministratorsEntity>()
                .eq(AdministratorsEntity::getUsername,administratorsEntity.getUsername())
        );
        if(Objects.isNull(trueAdministrators)){
            return false;
        }
        if(trueAdministrators.getPassword().equals(password)){

            //登录成功，把用户实体数据存 和 token存入数据库

            String token = JwtUtil.sign(administratorsEntity.getUsername(),administratorsEntity.getPassword());
            redisUtil.doRedis(trueAdministrators,token);
            return !StringUtils.isEmpty((String) redisUtil.get("prefix_user_entity_" + trueAdministrators.getUsername()));
        }
        return false;
    }

    @Override
    public AdministratorsEntity getUserByUserName(String userName) {
        AdministratorsEntity trueAdministrators = administratorsDao.getAdministratorsByUserName(userName);

        if(Objects.isNull(trueAdministrators)){
            return null;
        }
        return trueAdministrators;
    }

    @Override
    public int add(AdministratorsEntity administratorsEntity) {
        return administratorsDao.add(administratorsEntity);
    }
}
